package com.ruoyi.dataSet.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.dataSet.DTO.*;
import com.ruoyi.dataSet.service.DocumentService;
import com.ruoyi.system.domain.DsZsk;
import com.ruoyi.system.service.IDsZskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Anonymous
@RestController
@RequestMapping("/document")
public class DocumentController {

    @Autowired
    private DocumentService documentService;

    @Autowired
    private IDsZskService zskService;

    @PostMapping("/uploadToFolder")
    @PreAuthorize("@ss.hasPermi('deepSeek:document:createByFile')")
    public ResponseEntity<String> uploadDocumentToFolder(
        @RequestParam("folderId") Long folderId,
        @RequestParam("file") MultipartFile file) {
        try {
            // 1. 验证文件夹是否存在
            DsZsk folder = zskService.selectDsZskByZskId(folderId);
            if (folder == null || !"1".equals(folder.getFileFlag())) {
                return ResponseEntity.badRequest().body("Invalid folder ID");
            }

            // 2. 模拟的dify知识库ID
            String datasetId = "97755d27-9d05-4986-9331-40e9a603d6ba";

            // 3. 创建处理规则
            Map<String, Object> processRule = new HashMap<>();
            processRule.put("indexing_technique", "high_quality");

            Map<String, Object> rules = new HashMap<>();
            List<Map<String, Object>> preProcessingRules = new ArrayList<>();

            Map<String, Object> rule1 = new HashMap<>();
            rule1.put("id", "remove_extra_spaces");
            rule1.put("enabled", true);

            Map<String, Object> rule2 = new HashMap<>();
            rule2.put("id", "remove_urls_emails");
            rule2.put("enabled", true);

            preProcessingRules.add(rule1);
            preProcessingRules.add(rule2);

            Map<String, Object> segmentation = new HashMap<>();
            segmentation.put("separator", "###");
            segmentation.put("max_tokens", 500);

            rules.put("pre_processing_rules", preProcessingRules);
            rules.put("segmentation", segmentation);

            Map<String, Object> processRuleInner = new HashMap<>();
            processRuleInner.put("rules", rules);
            processRuleInner.put("mode", "custom");

            processRule.put("process_rule", processRuleInner);

            // 4. 上传文档到dify
            String documentResponse = documentService.createDocumentByFile(
                datasetId,
                new ObjectMapper().writeValueAsString(processRule),
                file
            );

            // 5. 在本地数据库创建文档记录
            DsZsk document = new DsZsk();
            document.setZskName(file.getOriginalFilename());
            document.setTeacherId(folder.getTeacherId());
            document.setClassId(folder.getClassId());
            document.setPId(folderId);
            document.setFileFlag("0"); // 0表示文件
            zskService.insertDsZsk(document);

            return ResponseEntity.ok(documentResponse);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("Error: " + e.getMessage());
        }
    }


    // 通过文本创建文档
    @PostMapping("/create")
    @PreAuthorize("@ss.hasPermi('deepSeek:document:add')")
    public String createDocument(@RequestBody DocumentCreateRequest request) {
        try {
            return documentService.createDocument(request.getDatasetId(), request);
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    // 通过文件创建文档
    @PostMapping("/createByFile")
    @PreAuthorize("@ss.hasPermi('deepSeek:document:createByFile')")
    public ResponseEntity<String> createDocumentByFile(
        @RequestParam("datasetId") String datasetId,
        @RequestParam("data") String data,
        @RequestParam("file") MultipartFile file) {
        try {
            return ResponseEntity.ok(documentService.createDocumentByFile(datasetId, data, file));
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error: " + e.getMessage());
        }
    }

    // 通过文本创建文档到指定文件夹
    @PostMapping("/createToFolder")
    @PreAuthorize("@ss.hasPermi('deepSeek:document:add')")
    public ResponseEntity<String> createDocumentToFolder(
        @RequestParam("folderId") Long folderId,
        @RequestParam("name") String name,
        @RequestParam("text") String text) {
        try {
            // 1. 验证文件夹是否存在
            DsZsk folder = zskService.selectDsZskByZskId(folderId);
            if (folder == null || !"1".equals(folder.getFileFlag())) {
                return ResponseEntity.badRequest().body("Invalid folder ID");
            }

            // 2. 模拟的dify知识库ID
            String datasetId = "97755d27-9d05-4986-9331-40e9a603d6ba";

            // 3. 创建文档请求对象
            DocumentCreateRequest request = new DocumentCreateRequest();
            request.setName(name);
            request.setText(text);
            request.setIndexingTechnique("economy");
//            request.setProcessRule("automatic");

            // 4. 创建文档到dify
            String documentResponse = documentService.createDocument(datasetId, request);

            // 5. 在本地数据库创建文档记录
            DsZsk document = new DsZsk();
            document.setZskName(name);
            document.setTeacherId(folder.getTeacherId());
            document.setClassId(folder.getClassId());
            document.setPId(folderId);
            document.setFileFlag("0"); // 0表示文件
            zskService.insertDsZsk(document);

            return ResponseEntity.ok(documentResponse);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("Error: " + e.getMessage());
        }
    }


    // 获取文档列表
    @PostMapping("/list")
    @PreAuthorize("@ss.hasPermi('deepSeek:document:list')")
    public String getDocuments(@RequestBody Document document, @RequestParam String page, @RequestParam String limit) {
        try {
            String datasetId = document.getDatasetId();
            return documentService.getDocuments(datasetId, page, limit);
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    // 删除文档
    @PostMapping("/delete")
    @PreAuthorize("@ss.hasPermi('deepSeek:document:delete')")
    public String deleteDocument(@RequestBody Document document) {
        try {
            String datasetId = document.getDatasetId();
            String documentId = document.getDocumentId();
            return documentService.deleteDocument(datasetId, documentId);
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    // 更新文档内容
    @PostMapping("/update")
    @PreAuthorize("@ss.hasPermi('deepSeek:document:update')")
    public String updateDocument(@RequestBody DocumentUpdateRequest request) {
        try {
            String datasetId = request.getDatasetId();
            String documentId = request.getDocumentId();
            return documentService.updateDocument(datasetId, documentId, request);
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }
}
